package com.edgclub.edg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.GzWebViewActivity;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.model.User;
import com.edgclub.edg.utils.util.CryptUtil;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.google.gson.reflect.TypeToken;

import java.util.TreeMap;

/**
 * edg资讯
 */
public class EDGNewsFragment extends GzBaseFragment {
	private Activity mActivity;


	private boolean isFirstLoad = true;

	WebView webView = null;
	private ProgressBar mProgressBar;
	private UserPrefUtils userPrefUtil;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActivity = getActivity();
		View rootView= inflater.inflate(R.layout.fragment_webview_layout, container, false);
		return rootView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(view);

	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if(isVisibleToUser && isFirstLoad){
			isFirstLoad = false;
			webView.loadUrl(ApiConfig.USER_INFORMATION);
		}else{

		}
	}

	private void initView(View view){
		mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar11);
		webView = (WebView) view.findViewById(R.id.webview);

		WebSettings settings = webView.getSettings();
//        // 自适应屏幕
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);
		settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
		settings.setJavaScriptEnabled(true);
		settings.setDatabaseEnabled(true);
		settings.setDomStorageEnabled(true);
		webView.setWebViewClient(new WebViewClient() {
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				//handler.cancel(); // Android默认的处理方式
				handler.proceed();  // 接受所有网站的证书
				//handleMessage(Message msg); // 进行其他处理
			}
		});

		webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
		webView.getSettings().setJavaScriptEnabled(true);

		webView.setWebChromeClient(new WebChromeClient() {

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				mProgressBar.setProgress(newProgress);
			}
		});

		webView.setWebViewClient(new WebViewClient() {
			private int running = 0;

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				mProgressBar.setVisibility(View.VISIBLE);
				if(!ApiConfig.USER_INFORMATION.equals(url)){
					Intent intent=new Intent(getActivity(), GzWebViewActivity.class);
					intent.putExtra("url",url);
					intent.putExtra("actbarTitle","EDG资讯");
					intent.putExtra("isHasTitle",false);
					startActivity(intent);
				}
				return true;// true表示此事件在此处被处理，不需要再广播

			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				running = Math.max(running, 1); // First request move it to 1.
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				try {
					if (--running == 0) {
						mProgressBar.setProgress(0);
						mProgressBar.setVisibility(View.GONE);
					}
					if (view == null) {
						view = webView;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(!"".equals(signText)) {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							webView.loadUrl("javascript:getSign('"+signText+"')");
							signText="";
						}
					});
				}
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
										String description, String failingUrl) {
				Toast.makeText(getActivity(), description,
						Toast.LENGTH_SHORT).show();
				mProgressBar.setVisibility(View.GONE);
			}
		});

	}


	/**
	 * //     *  android sdk api >= 17 时需要加@JavascriptInterface
	 * //     * @author fei
	 * //     *
	 * //
	 */
	private String shareTitle = "";
	private String shareImage = "";
	private String shareContent = "";
	private String signText="";
	Handler mHandler=new Handler();
	final class InJavaScriptLocalObj {
		@JavascriptInterface
		public void showShareContent(String content) {
			if (!"".equals(content)) {
				shareContent = content;
			}
		}

		@JavascriptInterface
		public void showShareTitle(String title) {
			if (!"".equals(title)) {
				shareTitle = title;
			}
		}

		@JavascriptInterface
		public void showShareImage(String image) {
			if (!"".equals(image)) {
				shareImage = image;
			}
		}

		@JavascriptInterface
		public void setInfo() {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					User user=userPrefUtil.getUser();
					user.setPsw("");
					user.setOldPwd("");
					user.setNewPwd("");
					user.setVersion(GuZhiApplication.getInstance().getVersion());
					String userjson= JsonUtil.getJsonStr(user);
					webView.loadUrl("javascript:getUserInfo('"+userjson+"')");
				}
			});
		}
		@JavascriptInterface
		public void setSign(final String sign) {
			if (null != sign && !"".equals(sign)) {
				TreeMap<String, String> params = new TreeMap<>();
				params = JsonUtil.getMode(sign, new TypeToken<TreeMap<String, String>>(){}.getType());
				signText= CryptUtil.sign(params, ApiConfig.HTTP_KEY);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						webView.loadUrl("javascript:getSign2('"+signText+"')");
						signText="";
					}
				});
			}
		}

	}

}
